<?php
require_once('../../carbox.php');

ignore_user_abort(TRUE);
ob_start( );
session_write_close( );

if(!carbox_check_session( ))
	header('Location: http://'.$_SERVER['HTTP_HOST'].'/carbox/login.php');

if (isset($_GET['zip_fileid'])){
	$filename = "/tmp/".$_GET['zip_fileid'].".zip";
	$filesize = filesize($filename);
	$blocksize = 2 << 20;
	$sent = 0;
	$handle =fopen($filename, 'r');
	header("Content-type: application/zip;");
	header("Content-Transfer-Encoding: Binary");
	header("Content-length: ".$filesize.";\n");
	header('Content-disposition: attachment; filename="'.$_GET['zip_fileid'].'.zip"');

	while($sent < $filesize) {
		echo fread($handle, $blocksize);
		flush( );
		ob_flush( );
		$sent += $blocksize;
	}
	die( );
}

$fn = $_GET['id'];
switch($_GET['mode']) {
	case "PROC_PAGE":
		$sql = "SELECT d.id, p.image FROM Page p INNER JOIN Document AS d ON p.document_id = d.id WHERE d.process_id = :id ORDER BY IFNULL(p.number_absolute, type_id), d.id";
		$fn = str_replace('/', '-', carbox_get_pn_by_pid($fn));
		break;
	case "ONLY_DOC":
		$sql = "SELECT d.id, p.image FROM Page p INNER JOIN Document AS d ON p.document_id = d.id WHERE d.id = :id ORDER BY p.number_relative";
		$fn = md5(microtime(true));
		break;
}
$query = end(carbox_query($sql, array(':id' => $_GET['id'])));
if($_GET['mode'] == "ONLY_DOC") {
	carbox_query(
		     "INSERT INTO DocumentAction (document_id, user_id, action_id, date) VALUES (:did, :uid, 4, NOW( ))",
		     array(':uid' => $_SESSION['uid'], ':did' => $query[0]["id"])
	);
}
$file_id = $fn;
$pn = "/tmp/carbox-zip-$file_id";
mkdir($pn);
$filename = "/tmp/".$file_id.".zip";
$img = new Imagick( );
for($i = 0; $i < count($query); ++$i){
	$img->clear( );
	$img->readImageBlob($query[$i]["image"]);
	$img->setFormat('JPG');
	file_put_contents("$pn/$file_id.jpg", $img->getImageBlob( ));
}
exec("zip -r $filename $pn");
ob_end_clean( );

?>
<script>
location.href = "zip.php?zip_fileid=<?=$file_id?>"
</script>
